package nxu.it.controller;

import io.jooby.Context;
import io.jooby.MediaType;
import io.jooby.ModelAndView;
import io.jooby.StatusCode;
import io.jooby.annotation.*;
import jakarta.inject.Singleton;
import nxu.it.dao.TodoStorage;
import nxu.it.dao.implement.MemoryTodoStorageImpl;
import nxu.it.model.Todo;

import java.util.*;

@Path("/todo")
@Singleton
public class Todocontroller {
    static TodoStorage todoStorage=new MemoryTodoStorageImpl();
    @GET(value="/list",produces = MediaType.HTML)
    public ModelAndView list(){
        ModelAndView mv=new ModelAndView("/todo/list.ftl", Map.of("todoList",todoStorage.list()));
        return mv;
    }

    @POST(value="/save",produces =MediaType.HTML)
    public void save(Context ctx, String content){
        todoStorage.save(new Todo(content));
        ctx.sendRedirect(StatusCode.SEE_OTHER,"/todo/list");
    }
    @GET(value="/check/{id}",produces = MediaType.HTML)
    public void check(Context ctx,@PathParam int id){
        todoStorage.check(id);
        ctx.sendRedirect(StatusCode.SEE_OTHER,"/todo/list");
    }
    @GET(value="/edit/{id}",produces = MediaType.HTML)
    public ModelAndView edit(Context ctx, @PathParam int id){
        Optional<Todo> todoOpt = todoStorage.get(id);
        if(todoOpt.isEmpty()){
            ctx.setResponseCode(StatusCode.NOT_FOUND_CODE);
            return new ModelAndView<>("not-found.ftl",Map.of());
        }
        ModelAndView mv=new ModelAndView("/todo/edit.ftl", Map.of("todo",todoOpt.get()));
        return mv;
    }
    @POST(value="/update",produces =MediaType.HTML)
    public void update(Context ctx, @FormParam Todo todo){
        todoStorage.update(todo);
        ctx.sendRedirect(StatusCode.SEE_OTHER,"/todo/list");
    }
    @GET(value="/delete/{id}",produces = MediaType.HTML)
    public void delete(Context ctx, @PathParam int id){
        todoStorage.delete(id);
        ctx.sendRedirect(StatusCode.SEE_OTHER,"/todo/list");
    }
}
